/*
 * Copyright (C) guolin, Suzhou Quxiang Inc. Open source codes for study only.
 * Do not use for commercial purpose.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bp.hearthealth.pulse.lnapps.bp_utils

import android.annotation.SuppressLint
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import java.util.TimeZone

/**
 * 时间和日期工具类。
 *
 */
object DateUtils {

    const val MINUTE = (60 * 1000).toLong()

    const val HOUR = 60 * MINUTE

    const val DAY = 24 * HOUR

    const val WEEK = 7 * DAY

    const val MONTH = 4 * WEEK

    const val YEAR = 365 * DAY

    /**
     * 根据传入的Unix时间戳，获取转换过后更加易读的时间格式。
     * @param dateMillis
     * Unix时间戳
     * @return 转换过后的时间格式，如2分钟前，1小时前。
     */
    fun getConvertedDate(dateMillis: Long): String {
        val currentMillis = System.currentTimeMillis()
        val timePast = currentMillis - dateMillis
        if (timePast > -MINUTE) { // 采用误差一分钟以内的算法，防止客户端和服务器时间不同步导致的显示问题
            when {
                /*timePast < HOUR -> {
                    var pastMinutes = timePast / MINUTE
                    if (pastMinutes <= 0) {
                        pastMinutes = 1
                    }
                    return pastMinutes.toString() + GlobalUtil.getString(R.string.minutes_ago)
                }*/
                timePast < DAY -> {
                    var pastHours = timePast / HOUR
                    if (pastHours <= 0) {
                        pastHours = 1
                    }
                    /*return pastHours.toString() + GlobalUtil.getString(R.string.hours_ago)*/
                    return getDateAndHourHm(dateMillis)
                }

                timePast < WEEK -> {
                    var pastDays = timePast / DAY
                    if (pastDays <= 0) {
                        pastDays = 1
                    }
                    return "$pastDays 天前"
                }

                timePast < MONTH -> {
                    var pastDays = timePast / WEEK
                    if (pastDays <= 0) {
                        pastDays = 1
                    }
                    return "$pastDays 周前"
                }

                else -> return getDate(dateMillis)
            }
        } else {
            return getDateAndTime(dateMillis)
        }
    }

    fun isBlockedForever(timeLeft: Long) = timeLeft > 5 * YEAR

    fun getDate(dateMillis: Long, pattern: String = "yyyy-MM-dd"): String {
        val sdf = SimpleDateFormat(pattern, Locale.getDefault())
        return sdf.format(Date(dateMillis))
    }

    fun getDateAndTime(dateMillis: Long): String {
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
        return sdf.format(Date(dateMillis))
    }

    fun getDateAndMD(dateMillis: Long): String {
        val sdf = SimpleDateFormat("MM.dd", Locale.getDefault())
        return sdf.format(Date(dateMillis))
    }

    fun getDateAndHourHm(dateMillis: Long): String {
        val sdf = SimpleDateFormat("HH:mm", Locale.getDefault())
        return sdf.format(Date(dateMillis))
    }

    /**
     * 将时间字符串转换为时间戳（毫秒）
     *
     * @param timeString 时间字符串，格式为 "HH:mm"
     * @return 时间戳（毫秒），转换失败返回 -1
     */
    fun stringToTimeStamp(timeString: String): Long {
        val dateFormat = SimpleDateFormat("HH。mm", Locale.getDefault())
        return try {
            val date = dateFormat.parse(timeString)
            date?.time ?: -1
        } catch (e: Exception) {
            e.printStackTrace()
            -1
        }
    }

    /**
     * 将日期字符串转换为时间戳（毫秒）
     *
     * @param dateString 日期字符串，格式为 "yyyyMMdd"
     * @param timeZone 时区，默认为 UTC
     * @return 时间戳（毫秒），转换失败返回 -1
     */
    fun stringToDateStamp(
        dateString: String,
        timeZone: TimeZone = TimeZone.getTimeZone("UTC")
    ): Long {
        val dateFormat = SimpleDateFormat("yyyyMMdd", Locale.getDefault())
        dateFormat.timeZone = timeZone
        return try {
            val date = dateFormat.parse(dateString)
            date?.time ?: -1
        } catch (e: Exception) {
            e.printStackTrace()
            -1
        }
    }

    fun getCurrentDateTimestamp(): Long {
        val calendar = Calendar.getInstance()
        calendar.timeZone = TimeZone.getTimeZone("UTC") // 设置时区为 UTC，以防止时区偏移影响结果
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)
        return calendar.timeInMillis
    }

    fun getCurrentTimeTimestamp(): Long {
        val calendar = Calendar.getInstance()
        calendar.timeZone = TimeZone.getTimeZone("UTC")
        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY))
        calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE))
        calendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND))
        calendar.set(Calendar.MILLISECOND, calendar.get(Calendar.MILLISECOND))
        return calendar.timeInMillis
    }

    fun timestampToyyyyMMdd(timestamp: Long): String {
        val sdf = SimpleDateFormat("yyyyMMdd", Locale.getDefault())
        return sdf.format(Date(timestamp))
    }
    fun nowTime(timestamp: Long): String {
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        return sdf.format(Date(timestamp))
    }

    //获取年月日；
    fun timestampToDate(timestamp: Long, format: String): String {
        val dateFormat = SimpleDateFormat(format, Locale.ENGLISH)
        return dateFormat.format(Date(timestamp))
    }

    //获取小时：分钟
    fun getCurrentTime(): String {
        val currentTime = Calendar.getInstance().time
        val dateFormat = SimpleDateFormat("HH:mm", Locale.ENGLISH)
        return dateFormat.format(currentTime)
    }

    fun getCurrentDate(): String {
        val currentDate = Calendar.getInstance().time
        val dateFormat = SimpleDateFormat("yyyyMMdd", Locale.ENGLISH)
        return dateFormat.format(currentDate)
    }

    //20220314 10:10 转时间戳
    fun dateTimeStringToTimestamp(dateTimeString: String, format: String): Long {
        val dateFormat = SimpleDateFormat(format, Locale.ENGLISH)
        val date = dateFormat.parse(dateTimeString)
        return date?.time ?: -1
    }

    /**
     * 获取当天的开始时间戳和结束时间戳
     */
    @SuppressLint("SimpleDateFormat")
    fun getStartAndEndOfTodayTimestamps(): Pair<Long, Long> {
        val startCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+0")).apply {
            set(Calendar.HOUR_OF_DAY, 0)
            set(Calendar.MINUTE, 0)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }


        val endCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+0")).apply {
            set(Calendar.HOUR_OF_DAY, 23)
            set(Calendar.MINUTE, 59)
            set(Calendar.SECOND, 59)
            set(Calendar.MILLISECOND, 999)
        }
        val startOfDay = startCalendar.timeInMillis
        val endOfDay = endCalendar.timeInMillis

        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        sdf.timeZone = TimeZone.getTimeZone("GMT+0")

        val startTime = sdf.format(Date(startOfDay))
        val endTime = sdf.format(Date(endOfDay))

//        LogUtil.i("Start Time: $startTime")
//        LogUtil.i("End Time: $endTime")

        return Pair(startOfDay, endOfDay)
    }

    fun thirtyDaysAgoStartTimestamp(): Long {
        // 获取当前时间的 Calendar 实例
        val calendar = Calendar.getInstance()
        // 获取当前时间的时间戳
        val currentTimeStamp = calendar.timeInMillis
        // 减去30天的毫秒数
        val thirtyDaysInMillis = 30L * 24 * 60 * 60 * 1000
        val thirtyDaysAgoTimeStamp = currentTimeStamp - thirtyDaysInMillis
        // 设置日期为30天前的开始时间（小时、分钟、秒和毫秒设置为0）
        calendar.timeInMillis = thirtyDaysAgoTimeStamp
        calendar[Calendar.HOUR_OF_DAY] = 0
        calendar[Calendar.MINUTE] = 0
        calendar[Calendar.SECOND] = 0
        calendar[Calendar.MILLISECOND] = 0
        // 获取30天前的开始时间戳
        return calendar.timeInMillis
    }

    fun getStartAndEndOfDay(timeInMillis: Long): Pair<Long, Long> {
        val startCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+0")).apply {
            setTimeInMillis(timeInMillis)
            set(Calendar.HOUR_OF_DAY, 0)
            set(Calendar.MINUTE, 0)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }


        val endCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+0")).apply {
            setTimeInMillis(timeInMillis)
            set(Calendar.HOUR_OF_DAY, 23)
            set(Calendar.MINUTE, 59)
            set(Calendar.SECOND, 59)
            set(Calendar.MILLISECOND, 999)
        }
        val startOfDay = startCalendar.timeInMillis
        val endOfDay = endCalendar.timeInMillis

        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        sdf.timeZone = TimeZone.getTimeZone("GMT+0")

        val startTime = sdf.format(Date(startOfDay))
        val endTime = sdf.format(Date(endOfDay))

        LogUtil.i("Start Time: $startTime")
        LogUtil.i("End Time: $endTime")

        return Pair(startOfDay, endOfDay)
    }

    /** 检查广告是否在 n 小时前加载。 */
    fun wasLoadTimeLessThanNHoursAgo(numHours: Long, loadTime: Long): Boolean {
        val dateDifference: Long = Date().time - loadTime
        val numMilliSecondsPerHour: Long = 3600000
        return dateDifference < numMilliSecondsPerHour * numHours
    }


}
